<template>
  <div class="shop-add-group">
    <el-row>
      <el-col :span="16" :offset="4">
        <el-form label-width="100px" label-position="right" :model="shopInfo">
          <el-form-item label="商户名">
            <el-input v-model="shopInfo.name" placeholder="请输入商户名"></el-input>
          </el-form-item>
          <el-form-item label="地址">
            <el-autocomplete style="width: 100%" v-model="shopInfo.address" :trigger-on-focus="false" :fetch-suggestions="querySearch" placeholder="请输入店铺地址"></el-autocomplete>
            <span>当前城市:{{city.name}}</span>
          </el-form-item>
          <el-form-item label="店铺简介">
            <el-input type="textarea" v-model="shopInfo.description" placeholder="请输入店铺简介" resize="none" maxlength="50" show-word-limit></el-input>
          </el-form-item>
          <el-form-item v-if="notUpdate" label="宣传口号">
            <el-input type="textarea" v-model="shopInfo.promotion_info" placeholder="请输入宣传口号" resize="none" maxlength="50" show-word-limit></el-input>
          </el-form-item>
          <el-form-item label="联系方式">
            <el-input v-model="shopInfo.phone" placeholder="请输入联系方式"></el-input>
          </el-form-item>
          <el-form-item label="营业时间" v-if="notUpdate">
            <el-time-select placeholder="开始时间" v-model="shopInfo.startTime" :picker-options="{
              start:'05:00',
              end:'23:00'
            }"></el-time-select>
            -
            <el-time-select placeholder="结束时间" v-model="shopInfo.endTime" :picker-options="{
              start:'05:00',
              end:'23:00',
              minTime:shopInfo.startTime
            }"></el-time-select>
          </el-form-item>
          <el-form-item label="平台税(%)">
            <el-input placeholder="请输入平台抽取税率" v-model="shopInfo.platform_rate"></el-input>
          </el-form-item>
          <el-form-item label="配送费" v-if="notUpdate">
            <el-input-number :max="15" :min="2" v-model="shopInfo.float_delivery_fee"></el-input-number>
          </el-form-item>
          <el-form-item label="起送价格" v-if="notUpdate">
            <el-input-number :max="200" :min="15" :step="5" v-model="shopInfo.float_minimum_order_amount"></el-input-number>
          </el-form-item>
          <el-form-item label="商户分类">
            <el-cascader v-model="shopInfo.categorySelect" :options="categoryList" :props="{children:'sub_categories',label:'name',value:'name'}" @change="formatterCategory"></el-cascader>
          </el-form-item>
          <el-form-item label="商户特色" v-if="notUpdate">
            <el-switch class="switch-style" v-model="shopInfo.is_premium" active-text="品牌保障"></el-switch>
            <el-switch class="switch-style" v-model="shopInfo.deliveryMode" active-text="蜂鸟专送"></el-switch>
            <el-switch class="switch-style" v-model="shopInfo.bao" active-text="超时赔付"></el-switch>
            <el-switch class="switch-style" v-model="shopInfo.zhun" active-text="准时达"></el-switch>
            <el-switch class="switch-style" v-model="shopInfo.piao" active-text="开发票"></el-switch>
          </el-form-item>
          <el-form-item label="店铺头像">
            <el-upload :action="uploadPath" :before-upload="beforeUpload" :on-success="imagePathSuccess" :headers="uploadHeader" :show-file-list="false">
              <el-button type="success">上传</el-button>
            </el-upload>
            <el-image v-if="imagePath.showImage" :src="imagePath.imagePath" style="width: 100px;height: 100px" :preview-src-list="imagePath.imagePrevList"></el-image>
          </el-form-item>
          <el-form-item label="营业执照" v-if="notUpdate">
            <el-upload :action="uploadPath" :before-upload="beforeUpload" :on-success="businessPathSuccess" :headers="uploadHeader" :show-file-list="false">
              <el-button type="success">上传</el-button>
            </el-upload>
            <el-image v-if="businessPath.showBusiness" :src="businessPath.businessPath" style="width: 100px;height: 100px" :preview-src-list="businessPath.businessPrevList"></el-image>
          </el-form-item>
          <el-form-item label="从业资格证" v-if="notUpdate">
            <el-upload :action="uploadPath" :before-upload="beforeUpload" :on-success="cateringPathSuccess" :headers="uploadHeader" :show-file-list="false">
              <el-button type="success">上传</el-button>
            </el-upload>
            <el-image v-if="cateringPath.showCatering" :src="cateringPath.cateringPath" style="width: 100px;height: 100px" :preview-src-list="cateringPath.cateringPrevList"></el-image>
          </el-form-item>
          <el-form-item>
            <el-button type="warning" @click="resetForm">重置</el-button>
            <el-button type="primary" @click="submitForm">保存</el-button>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>
  </div>
</template>

<script>
const initShop = {
  id: '',
  name: '',
  address: '',
  description: '',
  promotion_info: '',
  phone: '',
  startTime: '',
  endTime: '',
  platform_rate: '',
  float_delivery_fee: 5,
  float_minimum_order_amount: 20,
  categorySelect: [],
  category: '',
  is_premium: true,
  deliveryMode: true,
  bao: true,
  zhun: true,
  piao: true,
  image_path: '',
  business_license_image: '',
  catering_service_license_image: ''
}
export default {
  name: 'ShopEdit',
  data () {
    return {
      shopInfo: { ...initShop },
      city: {},
      categoryList: [],
      uploadPath: process.env.VUE_APP_BASE_API + 'file',
      uploadHeader: {
        Authorization: ''
      },
      imagePath: {
        imagePath: '',
        showImage: false,
        imagePrevList: []
      },
      businessPath: {
        businessPath: '',
        showBusiness: false,
        businessPrevList: []
      },
      cateringPath: {
        cateringPath: '',
        showCatering: false,
        cateringPrevList: []
      },
      loading: {},
      notUpdate: true
    }
  },
  methods: {
    getCity () {
      this.$http.get('/v1/cities', { type: 'guess' }).then(({ data }) => {
        if (data.code === 20000) {
          this.city = data.data
        }
      })
    },
    getCategory () {
      this.$http.get('shopping/v2/restaurant/category').then(({ data }) => {
        if (data.code === 20000) {
          this.categoryList = data.data
        }
      })
    },
    querySearch (query, back) {
      this.$http.get('v1/pois', { city_id: this.city.id, keyword: query }).then(({ data }) => {
        if (data.code === 20000) {
          const valueList = data.data.map(item => {
            return {
              value: item.address
            }
          })
          /* map方法的原理 */
          const valueList2 = []
          for (const item of data.data) {
            const valueObj = {
              value: item.address
            }
            valueList2.push(valueObj)
          }
          back(valueList)
        }
      })
    },
    formatterCategory (value) {
      this.shopInfo.category = value.join('/')
      // let str = ''
      // for (let i = 0; i < value.length; i++) {
      //   str += value[i]
      //   if (i < value.length - 1) {
      //     str += '/'
      //   }
      // }
    },
    beforeUpload (file) {
      const isType = (file.type === 'image/jpeg') || (file.type === 'image/png')
      if (!isType) {
        this.$message({
          message: '请上传正确格式的图片',
          type: 'error'
        })
      }
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isLt2M) {
        this.$message({
          message: '上传文件不能超过5M',
          type: 'error'
        })
      }
      return isType && isLt2M
    },
    imagePathSuccess (data) {
      if (data.code === 20000) {
        this.imagePath.showImage = true
        this.imagePath.imagePath = process.env.VUE_APP_BASE_API + 'file/getImgStream?fileName=' + data.data.realFileName
        this.imagePath.imagePrevList = [this.imagePath.imagePath]
        this.shopInfo.image_path = data.data.realFileName
      }
    },
    businessPathSuccess (data) {
      if (data.code === 20000) {
        this.businessPath.showBusiness = true
        this.businessPath.businessPath = process.env.VUE_APP_BASE_API + 'file/getImgStream?fileName=' + data.data.realFileName
        this.businessPath.businessPrevList = [this.businessPath.businessPath]
        this.shopInfo.business_license_image = data.data.realFileName
      }
    },
    cateringPathSuccess (data) {
      if (data.code === 20000) {
        this.cateringPath.showCatering = true
        this.cateringPath.cateringPath = process.env.VUE_APP_BASE_API + 'file/getImgStream?fileName=' + data.data.realFileName
        this.cateringPath.cateringPrevList = [this.cateringPath.cateringPath]
        this.shopInfo.catering_service_license_image = data.data.realFileName
      }
    },
    resetForm () {
      this.shopInfo = { ...initShop }
    },
    submitForm () {
      this.loading = this.$loading({ text: '提交...' })
      this.shopInfo.activitiesJson = JSON.stringify([{ icon_name: '减', name: '满减优惠', description: '满30减5，满60减8' }])
      // let url = ''
      // if (this.$route.query.id) {
      //   url = 'updateshop'
      // } else {
      //   url = 'addShop'
      // }
      this.$http.post('shopping/' + (this.$route.query.id ? 'updateshop' : 'addShop'), this.shopInfo).then(({ data }) => {
        this.loading.close()
        if (data.code === 20000) {
          this.$alert('保存成功').then(() => {
            this.resetForm()
            this.$router.push('shop')
          })
        } else {
          this.$alert('保存失败')
        }
      })
    },
    init () {
      if (this.$route.query.id) {
        this.notUpdate = false
        this.$http.get('/shopping/restaurant/' + this.$route.query.id).then(({ data }) => {
          if (data.code === 20000) {
            const shop = data.data
            this.shopInfo = {
              id: shop.id,
              name: shop.name,
              description: shop.description,
              address: shop.address,
              promotion_info: shop.promotion_info,
              phone: shop.phone,
              platform_rate: shop.platform_rate,
              float_delivery_fee: shop.float_delivery_fee,
              float_minimum_order_amount: shop.float_minimum_order_amount,
              startTime: shop.opening_hours[0].split('/')[0],
              endTime: shop.opening_hours[0].split('/')[1],
              category: shop.category,
              categorySelect: shop.category.split('/'),
              is_premium: shop.is_premium === 'true',
              deliveryMode: shop.delivery_mode !== undefined,
              zhun: shop.supports && shop.supports.filter(item => item.icon_name === '准').length === 1,
              bao: shop.supports && shop.supports.filter(item => item.icon_name === '保').length === 1,
              piao: shop.supports && shop.supports.filter(item => item.icon_name === '票').length === 1,
              image_path: shop.image_path,
              business_license_image: shop.license.business_license_image,
              catering_service_license_image: shop.license.catering_service_license_image
            }

            this.imagePath = {
              showImage: true,
              imagePath: process.env.VUE_APP_BASE_API + 'file/getImgStream?fileName=' + this.shopInfo.image_path,
              imagePrevList: [this.imagePath.imagePath]
            }

            this.businessPath = {
              showBusiness: true,
              businessPath: process.env.VUE_APP_BASE_API + 'file/getImgStream?fileName=' + this.shopInfo.business_license_image,
              businessPrevList: [this.businessPath.businessPath]
            }

            this.cateringPath = {
              showCatering: true,
              cateringPath: process.env.VUE_APP_BASE_API + 'file/getImgStream?fileName=' + this.shopInfo.business_license_image,
              cateringPrevList: [this.cateringPath.cateringPath]
            }
          }
        })
      }
    }
  },
  created () {
    this.init()
    this.$nextTick(() => {
      this.getCity()
      this.getCategory()
      this.uploadHeader.Authorization = this.$cookies.get('token')
    })
  }
  /*
  * 商户名
  * 地址
  * 简介
  * 联系方式
  * 平台税
  * 分类
  * 店铺头像
  *
  *
  *
  *
  * */
}
</script>

<style scoped lang="scss">
  .switch-style{
    margin-right: 35px;
  }
</style>
